<!DOCTYPE html>
<html>
<head>
    <title>鹿鹿泽健身卡券生成</title>
    <link rel="stylesheet" href="../static/css/minghu.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
</head>
<body>
    {% include 'show_ins_info.html' %}
    <hr>
    <h2>会员优惠券 / 折扣券生成</h2>
    <div>      
        <div id="queryVc"></div>
        <hr style="margin-bottom: 20px;">
        
        <div id="vcNameBox" class="form-row">
            <h4>卡类型</h4>
            <select id="vcNameSel" onchange="checkAmountValid();">
                <option value="代金券">代金券</option>
                <option value="折扣券">折扣券</option>
            </select>
        </div>

        </div id="dateSelBox">
            <div class="form-row"><h4>有效期起始日</h4><input id="startDate" type="date" onchange="checkDateValid();"></div>
            <div class="form-row"><h4>有效期结束日</h4><input id="endDate" type="date" onchange="checkDateValid();"></div>
            <div id="dateErrMsg"></div>
        </div>
        
        <div class="form-row">
            <h4 >发放给</h4>
            <div>
                <input id="cusIdName" style="width: 100px;" oninput="handleInput()">&nbsp;&nbsp;   
                <input id="allCus" type="checkbox" value="all_cus" onclick="switchCusNameBox();"><label for="allCus">所有会员</label>
            </div>
        </div>
        <div id="cusList" style="display: none;"></div>

        <div id="vcUseForBox" class="form-row">
            <h4>用于</h4>
            <select id="useFor">
                <option value="common">普通</option>
                <option value="cel-birthday">生日</option>
                <option value="cel-teacher">教师节</option>
                <option value="cel-woman">女神节</option>       
                <option value="cel-other">其他节日</option>
                <option value="deposit">定金</option>
            </select>
        </div>

        <div id="amountBox" class="form-row">
            <h4 id="amtTitle">金额</h4>
            <input id="amount" type="number" min=0 style="width:50px;" oninput="checkAmountValid();">
            &nbsp;&nbsp;
            <span id="unit">元</span>
        </div>

        
        <hr style="margin-bottom: 20px;">
        <div id="errMsg" style="margin-bottom: 20px;"></div>

        <div><button id="submitBtn" onclick="submit();">生成优惠券</button></div>
    </div>


    <script src="../static/js/common.js"></script>
    <script>
        let cus_list;
        let ins_list;
        let vcData; 
        let insId;
        let insRole;
        let insName;
        

        document.addEventListener("DOMContentLoaded",function(){
            // loginCheck();
            const insInfo=hideInsSelectBlockAndGetInsInfo();
            insName=insInfo['sessionInsName'];
            insId=insInfo['sessionInsId'];
            insRole=insInfo['sessionInsRole'];

             //教练角色不允许进入该页面，返回Index
             if(insRole==='ins'){
                window.location.replace('./index');
            }

            fetch('/get_cus_list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                // console.log(data);
                cus_list=data;
                // console.log(cus_list);
                  })
                .catch(error => console.error('Error:', error));

                fetch('/get_ins_list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                console.log('ins list:',data);


                 })
                .catch(error => console.error('Error:', error));    
                
                selectToday('startDate','date');
                selectToday('endDate','date');
                const dateErrMsg=document.getElementById('dateErrMsg');
                dateErrMsg.innerHTML='';

        });

        function checkDateValid(){
            const dateErrMsg=document.getElementById('dateErrMsg');
            dateErrMsg.innerHTML='';
            const startDate=document.getElementById('startDate').value;
            const endDate=document.getElementById('endDate').value;
            const diffDays=compareDatesOnly2(new Date(startDate),new Date(endDate));
            if(diffDays<0){
                dateErrMsg.style.fontSize='10px';
                dateErrMsg.style.color='red';
                dateErrMsg.style.marginLeft='120px';
                dateErrMsg.innerHTML=`结束日小于起始日。已将结束日改为与起始日同一天。`;
                selectDate(startDate,'endDate','date');
            }else{
                dateErrMsg.innerHTML='';
            }
        }

        function submitCheck(){
            let errCount=0;
            let errMsg='';
            const cusIdName=document.getElementById('cusIdName').value.trim();
            const allCusCheckBox = document.querySelector('input[id="allCus"]');
            if(!allCusCheckBox.checked){
                if(!cusIdName || cusIdName===''){
                    errCount+=1;
                    errMsg+='会员为空，'
                }
            }

            const amount=document.getElementById('amount').value.trim();
            if(!amount || amount==='' || amount===0 || amount==='0'){
                errCount+=1;
                    errMsg+='金额或折扣错误，'
            }

            errMsg=errMsg.slice(0,-1)+'。';
            if(errCount>0){
                return {'res':false,'msg':errMsg}
            }else{
                return {'res':true,'msg':''}
            }
        }

        function resetBox(){
            const cusNameInputBox=document.getElementById('cusIdName');
            const amountBox=document.getElementById('amount');
            const errMsg=document.getElementById('errMsg');
            errMsg.innerHTML='';
            cusNameInputBox.value='';
            amountBox.value='';

        }

        function submit(){
            const checkRes=submitCheck();
            if(!checkRes['res']){
                alert(checkRes['msg']);
                return
            }

            const currentDateTime=dateToString(new Date(),'dateTime');

            const vcName=document.getElementById('vcNameSel').value;
            const vcType=vcName==='代金券'?'sub':'discount';
            const startDate=document.getElementById('startDate').value;
            const endDate=document.getElementById('endDate').value;
            const useFor=document.getElementById('useFor').value;
            const amount=document.getElementById('amount').value;
           
            let insIdPage;
            if(insRole==='ins'){
                insIdPage=insId;
            }else{
                insIdPage=insId;
                //特殊，陆的情况
                if(insRole==='admin'){
                    if(insId==='LZADM002'){
                        insIdPage='LZINS001';
                    }
                    
                }
            }

            let cusName;
            const errMsg=document.getElementById('errMsg');
            errMsg.innerHTML='';
            const cusNameInput=document.getElementById('cusIdName').value.trim();
            const allCusCheckBox = document.querySelector('input[id="allCus"]');
            if(allCusCheckBox.checked){
                cusName='AL99999all_cus';
            }else{
                cusName=cusNameInput;
            }
            const vcId=`VC${dateToString(new Date(),'digit14')}`;
            const newVcData={
                'vcId':vcId,
                'vcType':vcType,
                'vcName':vcName,
                'amount':amount,
                'startDate':startDate,
                'endDate':endDate,
                'vcText':'',
                'useFor':useFor,
                'produceDatetime':currentDateTime,
                'oprId':insIdPage,
                'cusIdName':cusName
            }

            errMsg.innerHTML='正在生成优惠券';

            fetch('/write_new_vc',{
                method:"POST",
                headers:{
                    'Content-Type':'application/json'
                },
                body:JSON.stringify(newVcData)
            })
            .then(response=>response.json())
            .then(data=>{
                // console.log(data)
                if(data.res==='ok'){
                    console.log('write new vc card ok.')
                    errMsg.innerHTML=`优惠券生成成功`;
                    const msg=`为${cusName}生成了【${vcName}】\n券号 ${vcId}`;
                    alert(msg);
                    // window.location.replace('./index');
                    resetBox();
                }else{
                    const errMsg=data.msg;
                }
                
            })
            .catch(error=>{
                console.error('Error:',error.message)
            });
            

        }

        function checkAmountValid(){
            const errMsg=document.getElementById('errMsg');
            errMsg.innerHTML='';
            const vcName=document.getElementById('vcNameSel').value;
            const unit=document.getElementById('unit');
            const amt=document.getElementById('amount');
            const amtTitle=document.getElementById('amtTitle');
            if(vcName==='代金券'){
                amtTitle.textContent='金额';
                unit.textContent='元';
                if(parseFloat(amt.value.trim())<0){
                    errMsg.innerHTML=`代金券金额必须大于0`;
                    amt.value='';
                }
            }else{
                amtTitle.textContent='折扣';
                unit.textContent='';
                if(parseFloat(amt.value.trim())>1){
                    errMsg.innerHTML=`折扣系数必须小于1`;
                    amt.value='';
                }
            }



        }


        function switchCusNameBox(){
            const allCusCheckBox = document.querySelector('input[id="allCus"]');
            if(allCusCheckBox.checked){
                const cusIdName=document.getElementById('cusIdName');
                const cusList=document.getElementById('cusList');
                try{
                    
                    cusIdName.value='';
                    cusIdName.disabled=true;
                    cusList.innerHTML='';
                    cusList.style.display='none';

                }catch(error){

                }
            }else{
                cusIdName.disabled=false;
            }
        }
       
       

        function handleInput() {
            // 获取输入框中的值
            const searchTerm = document.getElementById("cusIdName").value.trim();
            const UpperSearchTerm=searchTerm.toUpperCase();
            // 获取展示结果的列表元素
            const resultList = document.getElementById("cusList");
 
     

            // 清空列表
            resultList.innerHTML = "";

            if (UpperSearchTerm === "") {
                resultList.style.display = "none";
                return; // 输入框为空，不做处理
            }else{
                resultList.style.display = "block";

            }

            // 遍历给定的数组，进行模糊匹配
            cus_list.reverse().forEach(function(name) {
                if (name.includes(UpperSearchTerm)) {
                    // 创建列表项元素，并设置其文本内容为匹配到的结果
                    const listItem = document.createElement("li");
                    listItem.textContent = name;

                    // 添加点击事件监听器
                    listItem.addEventListener("click", function() {
                        // 点击后将完整的姓名设置为输入框的值
                        document.getElementById("cusIdName").value = name;
                        resultList.style.display = "none";
                        resultList.innerHTML = "";
                    
                    });

                    // 将列表项添加到结果列表中
                    resultList.appendChild(listItem);

                    
                }else{
           

                }
            });
        
            resultList.classList.add("cus-list-result-blue");
            resultList.style.top='312px';
            resultList.style.left='134px';
            
        }
      

       
    </script>
    
</body>